package com.itheima.reggie.common;


import lombok.extern.slf4j.Slf4j;

import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.xml.bind.Element;
import java.sql.SQLIntegrityConstraintViolationException;

//第一种注解
//@ControllerAdvice(annotations = {RestController.class, Controller.class})
//@ResponseBody
//第二种注解
@RestControllerAdvice
//日志注解
@Slf4j
public class AllExceptHandle {

    @ExceptionHandler(DuplicateKeyException.class)
    public R<String> exceptionBySql(DuplicateKeyException ex) {
        //得到错误信息
        String msg = ex.getMessage();

        if (msg.contains("Duplicate entry")) {

            String[] s = msg.split(" ");
            String s1 = s[2];
            String s2 = s1.replace("'", "");
            return R.error(s2 + "用户名重复");
        }
        return R.error("添加失败，请检查重试");
    }

    //通过全局处理器捕获异常
    @ExceptionHandler(CusterException.class)
    public R<String> exception(CusterException ex) {
        return R.error(ex.getMessage());

    }

//    @ExceptionHandler(Exception.class)
//    public R<String> exception(Exception ex) {
//        return R.error("系统异常");
//
//    }
    /**
     * 异常处理方法
     * @return
//     */
//    @ExceptionHandler(CustomException.class)
//    public R<String> exception(CustomException ex) {
//        log.error(ex.getMessage());
//        return R.error(ex.getMessage());
//    }
}
